package com.lonwin.inspectionmanagement.mvp.ui.activity;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.geocoder.StreetNumber;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.lh.LhEarthSurfaceView;
import com.lh.LhSmoothEarthSurfaceView;
import com.lh.event.LhInputHandler;
import com.lh.features.LhCoordinate;
import com.lh.features.renderable.LhPointPlacemark;
import com.lh.kvlist.LhKVKey;
import com.lh.layers.LhLayer;
import com.lh.layers.LhLayerList;
import com.lh.util.LhCoordUtil;
import com.lonwin.inspectionmanagement.R;
import com.lonwin.inspectionmanagement.R2;
import com.lonwin.inspectionmanagement.app.AppConstants;
import com.lonwin.inspectionmanagement.app.service.LocationService;
import com.lonwin.inspectionmanagement.app.utils.AppUtil;
import com.lonwin.inspectionmanagement.app.utils.GPSUtil;
import com.lonwin.inspectionmanagement.app.utils.LhEarthUtils;
import com.lonwin.inspectionmanagement.app.utils.Listener.LhEarthListener;
import com.lonwin.inspectionmanagement.di.component.DaggerHomeComponent;
import com.lonwin.inspectionmanagement.di.module.HomeModule;
import com.lonwin.inspectionmanagement.mvp.contract.HomeContract;
import com.lonwin.inspectionmanagement.mvp.model.api.Api;
import com.lonwin.inspectionmanagement.mvp.model.api.AppConstant;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.ConfigBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.CreaQuestResultBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.GpsUpdataInfoBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.HhkqLhAliasBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.NLocusSResult;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.NeatentLocusBean;
import com.lonwin.inspectionmanagement.mvp.presenter.HomePresenter;
import com.lonwin.inspectionmanagement.mvp.ui.adapter.HomepopuwindowAdaptert;
import com.lonwin.inspectionmanagement.widget.BlurryPopupWindow;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static android.hardware.HardwareBuffer.RGBA_8888;
import static com.jess.arms.utils.Preconditions.checkNotNull;


public class HomeActivity extends BaseActivity<HomePresenter> implements HomeContract.View, LhEarthListener.ScreenMoveListener, GeocodeSearch.OnGeocodeSearchListener {

    @BindView(R2.id.home_LhEarthSurfaceView)
    LhEarthSurfaceView homeLhEarthSurfaceView;
    @BindView(R2.id.home_LinearLayout1)
    LinearLayout homeLinearLayout1;
    @BindView(R2.id.home_map_img)
    ImageView homeMapImg;
    @BindView(R2.id.home_location_img)
    ImageView homeLocationImg;
    @BindView(R2.id.home_LinearLayout2)
    LinearLayout homeLinearLayout2;
    @BindView(R2.id.home_address)
    TextView homeAddress;
    @BindView(R2.id.home_address_range)
    TextView homeAddressRange;
    @BindView(R2.id.home_pointRecording)
    TextView homePointRecording;
    @BindView(R2.id.home_startCruise)
    TextView homeStartCruise;
    @BindView(R2.id.home_LinearLayout_default)
    LinearLayout homeLinearLayoutDefault;
    @BindView(R2.id.home_LinearLayout3)
    LinearLayout homeLinearLayout3;
    @BindView(R2.id.home_CruiseRecordingActivity)
    TextView home_CruiseRecordingActivity;
    @BindView(R2.id.home_name_txt)
    TextView home_name_txt;
    @BindView(R2.id.home_RecyclerView)
    RecyclerView home_RecyclerView;

    @BindView(R2.id.home_intermediate_img)
    ImageView home_intermediate_img;

    @BindView(R2.id.home_Cruise_poing_lay)
    LinearLayout home_Cruise_poing_lay;
    @BindView(R2.id.home_Cruise_poing_ts_txt)
    TextView home_Cruise_poing_ts_txt;
    @BindView(R2.id.home_Cruise_poing_txt)
    TextView home_Cruise_poing_txt;
    @BindView(R2.id.home_tip_txt)
    TextView home_tip_txt;

    @Inject
    RxPermissions mRxPermissions;
    private int mselectId;
    private GeocodeSearch geocodeSearch;
    private HomepopuwindowAdaptert homepopuwindowAdapter;
    private String showType = "home";//home point
    private LhEarthListener lhEarthListener;
//    private AMapLocation maMapLocation;
    private MediaProjectionManager mediaProjectionManager;
        private double lat=0.0;
        private double lont=0.0;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerHomeComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .homeModule(new HomeModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_home; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter.getCondig();
        homepopuwindowAdapter = new HomepopuwindowAdaptert(new ArrayList<>());
        home_RecyclerView.setLayoutManager(new LinearLayoutManager(HomeActivity.this));
        home_RecyclerView.setAdapter(homepopuwindowAdapter);
        geocodeSearch = new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(this);
        mPresenter.nextActivity();
        LhEarthUtils.addLayers(homeLhEarthSurfaceView,mPresenter.getConfigBean());
        lhEarthListener = new LhEarthListener(this, homeLhEarthSurfaceView);
        homeLhEarthSurfaceView.setInputHandler(lhEarthListener);
        setListeners();
        homeMapImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                homeMapImg.post(new Runnable() {
                    @Override
                    public void run() {
                        LhEarthUtils.setHide(homeLhEarthSurfaceView);
                    }
                });

            }
        });
    }


    public void setListeners() {
        homeLocationImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //从新请求定位
                mPresenter.nextActivity();
            }
        });
        home_name_txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                home_RecyclerView.setVisibility(View.VISIBLE);

                AppUtil.setAnimator(home_RecyclerView);
                homepopuwindowAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        mselectId = position;
                        home_RecyclerView.setVisibility(View.GONE);
                    }
                });
            }
        });
        home_Cruise_poing_txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到创建打点界面
            }
        });
        homeStartCruise.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(HomeActivity.this, HomeCruiseActivity.class);
                intent.putExtra("lat", lat);
                intent.putExtra("lont", lont);
                startActivityForResult(intent,1002);
            }
        });
        home_CruiseRecordingActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(HomeActivity.this, NewCruiseRecordActivity.class);
                startActivity(intent);
            }
        });
        homePointRecording.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (lat==0||lont==0){
                    showMessage("定位出问题了");
                    return;
                }
//
                CreatPointRecordActivity.startCreatPointActivity(HomeActivity.this,"",CreatPointRecordActivity.Type.ADD,"创建问题",1001,lat,lont);
            }
        });
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this,message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public RxPermissions getRxPermissions() {
        return mRxPermissions;
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void queryHhkqLhAliasSuccerss(List<HhkqLhAliasBean.DataBean> dataBeans) {

        mPresenter.showPopuwindow(dataBeans, new HomePresenter.PopuWindowsClick() {
            @Override
            public void clickItem(HhkqLhAliasBean.DataBean dataBean, int selectId) {
                mselectId = selectId;
                Log.i("####", new Gson().toJson(dataBean));
                home_name_txt.setText(dataBean.getAlias());
            }
        });
    }

    @Override
    public void setConfig(ConfigBean config) {
//        if (config.getCurrentRole().getRoleCode().equals("Role_LLBM")||config.getCurrentRole().getRoleCode().equals("Role_LLY")||config.getCurrentRole().getRoleCode().equals("Role_HZ"))
//        {
//            mPresenter.queryHhkqLhAlias(config.getProjectId(), config.getAdcd(), "0", config.getGpsId()+"", config.getCurrentRole().getRoleID()+"");
//        }else {
//            mPresenter.queryHhkqLhAlias(config.getProjectId(), config.getAdcd(), "1", config.getGpsId()+"", config.getCurrentRole().getRoleID()+"");
//        }


    }

    @Override
    public void getCheckCount(String content, int num) {
        home_tip_txt.setVisibility(View.VISIBLE);
        home_tip_txt.setText(content);
        if (num>0)
        {
            home_tip_txt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(HomeActivity.this,UpcomingListActivity.class));
                }
            });
        }else {
            home_tip_txt.setVisibility(View.GONE);
        }
    }


    @Override
    public void onResume() {
        super.onResume();

//        homeLhEarthSurfaceView.onResume();
        EventBus.getDefault().register(this);
        mPresenter.getHzUnCheckXcjlbCount();
    }

    @Override
    public void onPause() {
        super.onPause();
//        homeLhEarthSurfaceView.onPause(); // pauses the rendering thread
        home_Cruise_poing_lay.setVisibility(View.GONE);
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onMoveListener(LhCoordinate lhCoordinate) {
        lat = lhCoordinate.getLatitude();
        lont=lhCoordinate.getLongitude();
        //移动后获取导经纬度
        //wgs84 转高德坐标系
        //wgs84 转高德坐标系
        double[] latlont=GPSUtil.gps84_To_Gcj02(lhCoordinate.getLatitude(),lhCoordinate.getLongitude());
        LatLonPoint latLonPoint = new LatLonPoint(latlont[0], latlont[1]);
//        LatLonPoint latLonPoint = new LatLonPoint(lhCoordinate.getLatitude(), lhCoordinate.getLongitude());
       final RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 100f, GeocodeSearch.AMAP);
        //异步查询
        geocodeSearch.getFromLocationAsyn(query);
        //========================================================================================
//        io.reactivex.Observable.create(new ObservableOnSubscribe<RegeocodeResult>() {
//            @Override
//            public void subscribe(ObservableEmitter<RegeocodeResult> emitter) throws Exception {
//
//            }
//        })
//
//      Flowable.create(new FlowableOnSubscribe<RegeocodeResult>() {
//
//           @Override
//           public void subscribe(FlowableEmitter<RegeocodeResult> emitter) throws Exception {
//               geocodeSearch.getFromLocationAsyn(query);
//               geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
//                   @Override
//                   public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
//                       emitter.onNext(regeocodeResult);
//                   }
//
//                   @Override
//                   public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
//
//                   }
//               });
//           }
//       },BackpressureStrategy.LATEST).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<RegeocodeResult>() {
//           @Override
//           public void accept(RegeocodeResult regeocodeResult) throws Exception {
//               ArmsUtils.makeText(HomeActivity.this,new Gson().toJson(regeocodeResult));
//           }
//       }).dispose();
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
        StringBuilder temAdderss = new StringBuilder();
        String province = regeocodeAddress.getProvince();//省
        String city = regeocodeAddress.getCity();//州市
        String count = regeocodeAddress.getDistrict();//县区
        String shipaddress = regeocodeAddress.getTownship();//村、街道
        String formataddress = regeocodeAddress.getFormatAddress();//完整的地址
        StreetNumber streetNumber = regeocodeAddress.getStreetNumber();//具体哪条路和门牌号
        String streetNumberStr = streetNumber.getStreet() + streetNumber.getNumber();//具体哪条路和门牌号字符串
        int index = formataddress.indexOf(shipaddress);
        String mapaddress = formataddress.substring(index + shipaddress.length(), formataddress.length());

        String temHtml = "";
        String firstAddress = "";
        String subAddress = "";
        if (formataddress.length() > temAdderss.append(province).append(city).append(count).append(shipaddress).toString().length()) {
            temHtml = "<font color='#494949'size='14'>" + formataddress.substring(temAdderss.length(), formataddress.length()) + "</font><br> <font color='#888888'size='10'>" + count + shipaddress + "</font>";
            firstAddress = formataddress.substring(temAdderss.length(), formataddress.length());
            subAddress = count + shipaddress;
        } else {
            if (shipaddress != null && shipaddress.length() > 0) {
                temHtml = "<font color='#494949'size='14'>" + shipaddress + "</font><br> <font color='#888888'size='10'>" + city + count + "</font>";
                firstAddress = shipaddress;
                subAddress = city + count;
            } else {
                temHtml = "<font color='#494949'size='14'>" + city + count + "</font><br> <font color='#888888'size='10'>" + province + "</font>";
                firstAddress = city + count;
                subAddress = province;
            }
        }
        homeAddress.setText(firstAddress);
        homeAddressRange.setText(subAddress);
        Log.i("###", temHtml);
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    @Subscriber(mode = ThreadMode.MAIN)
    public void reciverLocation(AMapLocation aMapLocation) {
        lat = aMapLocation.getLatitude();
        lont=aMapLocation.getLongitude();
        //接收到定位信息
        LhEarthUtils.locatPosition(homeLhEarthSurfaceView, LhCoordinate.fromDegrees(aMapLocation.getLatitude(), aMapLocation.getLongitude()));//25.07263654159436,102.66734565340529
        homeAddress.setText(aMapLocation.getStreetNum() == null ? (aMapLocation.getStreet() == null ? (aMapLocation.getCity() == null ? aMapLocation.getProvince() : (aMapLocation.getProvince() + aMapLocation.getCity())) : aMapLocation.getStreet()) : aMapLocation.getStreetNum());
        homeAddressRange.setText(aMapLocation.getAddress() != null ? aMapLocation.getAddress() : (aMapLocation.getStreetNum() == null ? (aMapLocation.getStreet() == null ? (aMapLocation.getCity() == null ? aMapLocation.getProvince() : (aMapLocation.getProvince() + aMapLocation.getCity())) : aMapLocation.getStreet()) : aMapLocation.getStreetNum()));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data==null)
        {
            return;
        }
        home_Cruise_poing_lay.setVisibility(View.VISIBLE);
        if (mPresenter.getConfigBean().getRiverDatas()!=null&&mPresenter.getConfigBean().getRiverDatas().size()==1&&mPresenter.getConfigBean().getRiverDatas().get(0).getChildren()!=null&&mPresenter.getConfigBean().getRiverDatas().get(0).getChildren().size()==1)
        {
              //只有一条河湖
              switch (requestCode){
                  case 1001:
                      CreaQuestResultBean.DataBean dataBean=(CreaQuestResultBean.DataBean)data.getSerializableExtra(AppConstant.CREATPOINT);
                      //从打点记录里回来
                      home_Cruise_poing_ts_txt.setText("问题已记录，可以在“巡查记录”里查看");
                      home_Cruise_poing_txt.setText("查看问题");
                      home_Cruise_poing_txt.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {

                          CreatPointRecordActivity.startCreatPointActivity(HomeActivity.this,dataBean.getQuestid(),CreatPointRecordActivity.Type.ONLYONE,"查看问题");
                      }
                  });
                      break;
                  case 1002:
                      //从记录轨迹归来
                      NLocusSResult.DataBean dataBean1;
                      if (data.hasExtra("NLocusSResultDataBean"))
                      {
                           dataBean1=(NLocusSResult.DataBean)data.getSerializableExtra("NLocusSResultDataBean");
                          home_Cruise_poing_ts_txt.setText("轨迹已记录，请在“巡查记录”里查看");
                          home_Cruise_poing_txt.setText("查看轨迹");
                          home_Cruise_poing_txt.setOnClickListener(new View.OnClickListener() {
                              @Override
                              public void onClick(View v) {
                                  CruiseLocusActivity.startCruiseLocusActivity(HomeActivity.this,dataBean1.getGjid(),CruiseLocusActivity.Type.ONE,"查看轨迹");                          }
                          });
                      }else {
                          home_Cruise_poing_lay.setVisibility(View.GONE);
                      }

                      break;
              }

                  return;
          }
          //两条和以上
        switch (requestCode){
            case 1001:
                CreaQuestResultBean.DataBean dataBean=(CreaQuestResultBean.DataBean)data.getSerializableExtra(AppConstant.CREATPOINT);
                home_Cruise_poing_ts_txt.setText("问题已记录，但还未关联到河湖");
                home_Cruise_poing_txt.setText("编辑问题");
                home_Cruise_poing_txt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                       CreatPointRecordActivity.startCreatPointActivity(HomeActivity.this,dataBean.getQuestid(),CreatPointRecordActivity.Type.EDIT,"编辑问题");
                    }
                });
                break;

            case 1002:
                //从记录轨迹归来
                NLocusSResult.DataBean dataBean1;
                if (data.hasExtra("NLocusSResultDataBean"))
                {
                    dataBean1=(NLocusSResult.DataBean)data.getSerializableExtra("NLocusSResultDataBean");
                    home_Cruise_poing_ts_txt.setText("轨迹已记录，但还未关联到河湖");
                    home_Cruise_poing_txt.setText("编辑轨迹");
                    home_Cruise_poing_txt.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            CruiseLocusActivity.startCruiseLocusActivity(HomeActivity.this,dataBean1.getGjid(),CruiseLocusActivity.Type.EDIT,"编辑轨迹");                          }
                    });
                }else {
                    home_Cruise_poing_lay.setVisibility(View.GONE);
                }
                break;
        }

    }
}
